package com.weiguan.xmpp.test;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.locks.ReentrantLock;

import org.jivesoftware.smack.tcp.XMPPTCPConnection;
import org.jivesoftware.smackx.muc.MultiUserChat;
import org.jivesoftware.smackx.muc.MultiUserChatManager;

import com.weiguan.xmpp.api.XmppRestApi;
import com.weiguan.xmpp.util.XMPPTCPConnectionUtils;

public class ThreadTask implements Runnable {

	private Thread thread = new Thread(this);

	private String roomName;
	private long beginUserId = 0;
	private int addCount;
	private int millis = 3000;
	private boolean isStart = false;

	private List<XMPPTCPConnection> cons = new ArrayList<XMPPTCPConnection>();

	private ReentrantLock lock = new ReentrantLock();

	public ThreadTask(long roomName, int addCount) {
		this.roomName = String.valueOf(roomName);
		this.beginUserId = Long.parseLong(roomName + "00001");
		this.addCount = addCount;
	}

	public void start() {
		isStart = true;
		thread.start();
	}

	public void stop() {
		synchronized (lock) {
			for (XMPPTCPConnection con : cons) {
				if (con != null && con.isConnected()) {
					con.disconnect();
				}
			}
			isStart = false;
		}
	}

	@Override
	public void run() {
		for (int i = 0; i < addCount; i++) {
			synchronized (lock) {
				if (!isStart) {
					break;
				}
				String userName = String.valueOf(beginUserId + i);
				XmppRestApi.createUser(userName, userName);

				XMPPTCPConnection con = XMPPTCPConnectionUtils.getXMPPTCPConnection(TaskHelp.serviceName, TaskHelp.host, userName, userName);

				if (con != null) {
					MultiUserChat muc = MultiUserChatManager.getInstanceFor(con).getMultiUserChat(roomName + "@conference." + con.getServiceName());
					String name = "test" + i;
					// 用户加入聊天室
					try {
						muc.join(userName + ":" + name + ":0");
						System.out.println(userName + " 加入房间成功!");
					} catch (Exception e) {
						System.out.println(userName + " 加入房间失败!");
					}
					cons.add(con);
				} else {
					System.out.println(userName + " 登陆失败!");
				}
			}
			try {
				Thread.sleep(millis);
			} catch (Exception e) {
				e.printStackTrace();
			}

		}

		while (isStart) {
			try {
				Thread.sleep(10);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
}
